package cn.yunchongbao.charging.order.service.impl;

import cn.yunchongbao.charging.common.pojo.JsonResult;
import cn.yunchongbao.charging.common.pojo.utils.JsonUtils;
import cn.yunchongbao.charging.common.pojo.vo.GunStatusUpdateParam;
import cn.yunchongbao.charging.common.pojo.vo.StationInfoVo;
import cn.yunchongbao.charging.common.pojo.vo.UserInfoVo;
import cn.yunchongbao.charging.order.constant.Constant;
import cn.yunchongbao.charging.order.constant.MqttConstant;
import cn.yunchongbao.charging.order.feign.DeviceClient;
import cn.yunchongbao.charging.order.feign.UserClient;
import cn.yunchongbao.charging.order.mqtt.MqttProducer;
import cn.yunchongbao.charging.order.pojo.dto.ChargingDto;
import cn.yunchongbao.charging.order.pojo.dto.StationInfoDto;
import cn.yunchongbao.charging.order.pojo.dto.UserInfoDto;
import cn.yunchongbao.charging.order.pojo.param.OrderAddParam;
import cn.yunchongbao.charging.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//import org.springframework.core.ParameterizedTypeReference;
//import org.springframework.http.HttpMethod;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.client.RestTemplate;

import java.util.Random;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Override
    public String createOrder(OrderAddParam orderAddParam) {
        //创建订单编号
        String  orderNo = getOrderNo();
        log.debug("开始生产订单号：{}", orderNo);
        //获取运营商和场站信息
        log.debug("获取运营商和场站信息入参：枪Id{}", orderAddParam.getGunId());
        StationInfoDto stationInfoDto = getStationInfoByGunId(orderAddParam.getGunId());
        log.debug("获取运营商和场站信息入参：枪Id{}，出参：{}", orderAddParam.getGunId(),stationInfoDto);
        //获取用户车辆信息
        log.debug("获取用户车辆信息入参：用户Id{}", orderAddParam.getUserId());
        UserInfoDto userInfoDto = getUserInfoByUserIdByFeign(orderAddParam.getUserId());
        log.debug("获取用户车辆信息入参：用户Id{}，出参：{}",orderAddParam.getUserId(), userInfoDto);
        //修改充电枪状态
        log.debug("修改充电枪状态入参：枪Id{}", orderAddParam.getGunId());
        Boolean Success = updateGunStatus(orderAddParam.getGunId());
        log.debug("修改充电枪状态入参：枪Id{}，出参：{}", orderAddParam.getGunId(), Success);
        //检查用户余额
        //给充电桩发送开始充电指令
        log.debug("给充电桩发送开始充电指令入参：订单编号：{}，桩Id：{}，枪Id：{}", orderNo,orderAddParam.getPileId(),orderAddParam.getGunId());
        sendStartChargingMessageToDevice(orderNo,orderAddParam.getPileId(),orderAddParam.getGunId());
        log.debug("成功给充电桩发送开始充电指令入参：订单编号：{}，桩Id：{}，枪Id：{}", orderNo,orderAddParam.getPileId(),orderAddParam.getGunId());
        return orderNo;
    }

    // 根据用户编号获取用户信息
//    @Autowired
//    private RestTemplate restTemplate;

    @Autowired
    private UserClient userClient;
    // 获取用户信息
    private UserInfoDto getUserInfoByUserIdByFeign(Integer userId){
        JsonResult<UserInfoVo> userInfo = userClient.getUserInfoFeign(userId);
        if(userInfo != null){
            UserInfoVo userInfoVo = userInfo.getData();
            if(userInfoVo != null){
                UserInfoDto userInfoDto = new UserInfoDto();
                userInfoDto.setCarId(userInfoVo.getCarId());
                return userInfoDto;
            }
        }
        return null;
    }
//    private UserInfoDto getUserInfoByUserIdByRestTemplate(Integer userId) {
//
//        // 获取用户信息
//        ParameterizedTypeReference<JsonResult<UserInfoVo>> parameterizedTypeReference = new ParameterizedTypeReference<JsonResult<UserInfoVo>>() {
//        };
//        String url = chooseUrl();
//        ResponseEntity<JsonResult<UserInfoVo>> entity = restTemplate.exchange(url, HttpMethod.GET, null, parameterizedTypeReference, userId);
//        if(entity != null){
//            HttpStatus statusCode = entity.getStatusCode();
//            if (HttpStatus.OK == statusCode){
//                JsonResult<UserInfoVo> body = entity.getBody();
//                UserInfoVo data = body.getData();
//                UserInfoDto userInfoDto = new UserInfoDto();
//                userInfoDto.setCarId(data.getCarId());
//                return userInfoDto;
//            }
//
//        }
//        return null;
//    }
//
//    private String chooseUrl() {
//        String url_8081 = "http://localhost:8081/user/info/{userId}";
//        String url_8082 = "http://localhost:8082/user/info/{userId}";
//        String url_8083 = "http://localhost:8083/user/info/{userId}";
//        String[] url_arr = {url_8081,url_8082,url_8083};
//        Random random = new Random();
//        int index = random.nextInt(url_arr.length);
//        String url = url_arr[index];
//        log.debug("获取的URL：{}", url);
//        return url;
//    }
    @Autowired
    private DeviceClient deviceClient;
    // 根据充电枪编号获取场站信息
    private StationInfoDto getStationInfoByGunId(Integer gunId) {
        JsonResult<StationInfoVo> stationInfo = deviceClient.getStationInfo(gunId);
        if(stationInfo != null){
            StationInfoVo stationInfoVo = stationInfo.getData();
            if(stationInfoVo != null){
                StationInfoDto stationInfoDto = new StationInfoDto();
                BeanUtils.copyProperties(stationInfoVo, stationInfoDto);
                return stationInfoDto;
            }

        }
        return null;
    }

    // 修改充电枪状态
    private Boolean updateGunStatus(Integer gunId) {
        GunStatusUpdateParam gunStatusUpdateParam = new GunStatusUpdateParam();
        gunStatusUpdateParam.setGunId(gunId);
        gunStatusUpdateParam.setStatus(Constant.GUN_STATUS_BUSY);
        JsonResult<Boolean> booleanJsonResult = deviceClient.gunStatusUpdate(gunStatusUpdateParam);
        if(booleanJsonResult != null){
            return booleanJsonResult.getData();
        }
        return false;
    }


    // 获取订单编号
    private String getOrderNo(){
        String start = "10000";
        long now = System.currentTimeMillis();
        Random random = new Random();
        int r = random.nextInt(100);
        String orderNo = start + "_" + r + "_" + now;
        return orderNo;
    }
    @Autowired
    private MqttProducer mqttProducer;
    // 给设备发送开始充电指令
    private void sendStartChargingMessageToDevice(String orderNo, Integer pileId, Integer gunId) {
        String topic = MqttConstant.TOPIC_START_CHARGING_PREFIX + pileId;
        ChargingDto chargingDto = new ChargingDto();
        chargingDto.setOrderNo(orderNo);
        chargingDto.setPileId(pileId);
        chargingDto.setGunId(gunId);
        String msg = ("0x55" + String.format("%02d", pileId) + String.format("%02d", gunId) + Constant.START_CHARGING + "000000000");
        chargingDto.setMsg(msg);
        String json = JsonUtils.toJson(chargingDto);
        log.debug("给设备发送开始充电指令到设备topic：{}，消息：{}",topic,chargingDto);
        mqttProducer.send(topic,json);
        log.debug("给设备发送开始充电指令到设备成功topic：{}，消息：{}",topic,chargingDto);
    }
}
